-- don't load if class is wrong
local _, class = UnitClass("player")
if class ~= "WARRIOR" then return end

local emod = clcInfo.env


-- ---------------------------------------------------------------------------------------------------------------------
-- MULTIPLE TARGET REND TRACKING - Experimental
-- ---------------------------------------------------------------------------------------------------------------------
-- CLEU EVENTS TO TRACK
-- SPELL_AURA_APPLIED -> dot applied 
-- SPELL_AURA_REFRESH -> dot refresh
-- SPELL_AURA_REMOVED -> dot removed
-- ---------------------------------------------------------------------------------------------------------------------

do
	local ef, list, playerName
	playerName = UnitName("player")
	local rendName, rendId, rendSpellTexture
	rendId = 94009
	rendName, _, rendSpellTexture = GetSpellInfo(rendId)
	
	local function ExecCleanup()
		list = nil
		ef:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
		ef.registered = false
	end
	
	-- starts to track the hot for that guid
	local function SPELL_AURA_APPLIED(guid, name)
		list[guid] = { name, 15, GetTime() + 15 }
	end
	
	local function SPELL_AURA_REFRESH(guid, name)
		local old = list[guid]
		if not old then return SPELL_AURA_APPLIED(guid, name) end
		
		local gt = GetTime()
		local nd = (old[3] - gt) % 3 + 15
		list[guid][2] = nd
		list[guid][3] = gt + nd
	end
	
	local function SPELL_AURA_REMOVED(guid)
		list[guid] = nil
	end
	
	local function CLEU(frame, event, timestamp, combatEvent, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags, spellId, spellName, spellSchool, spellType, dose, ...)
		if spellId == rendId and sourceName == playerName then
			if combatEvent == "SPELL_AURA_APPLIED" then
				SPELL_AURA_APPLIED(destGUID, destName)
			elseif combatEvent == "SPELL_AURA_REFRESH" then
				SPELL_AURA_REFRESH(destGUID, destName)
			elseif combatEvent == "SPELL_AURA_REMOVED" then
				SPELL_AURA_REMOVED(destGUID)
			end
		end
	end
	
	function emod.MBarRend(a1, a2, timeRight)
		-- setup the table for rend data
		if not list then
			list = {}
			emod.___e.ExecCleanup = ExecCleanup
		end
	
		-- setup CLEU monitoring
		if not ef then
			ef = CreateFrame("Frame")
			ef:Hide()
			ef:SetScript("OnEvent", CLEU)
		end
		if not ef.registered then
			ef:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
			ef.registered = true
		end
		
		-- go through the saved data
		-- delete the ones that expired
		-- display the rest
		local gt = GetTime()
		local value, tr, alpha
		for k, v in pairs(list) do
			-- 3 = expires
			if gt > v[3] then
				list[k] = nil
			else
				value = v[3] - gt
				if timeRight then
					tr = tostring(math.floor(value + 0.5))
				else
					tr = ""
				end
				if k == UnitGUID("target") then
					alpha = a1
				else
					alpha = a2
				end
				
				emod.___e:___AddBar(nil, alpha, nil, nil, nil, nil, rendSpellTexture, 0, v[2], value, "normal", v[1], "", tr)
			end
		end
	end
end
